import os
import re
import time
import platform
from dataclasses import dataclass

from conf.setting import BASE_PATH
from src.config_util import Config
from src.common import seconds_to_time


@dataclass
class TestMetrics:
    """ 用例执行数据 """
    total: int
    passed: int
    failed: int
    error: int
    skipped: int
    deselected: int
    xfailed: int
    xpassed: int
    warnings: int
    pass_rate: float
    duration: str
    failed_cases: list


def collect_test_result(terminalreporter):
    failed_cases = list()
    path_info_re = re.compile(r"<TestReport '(?P<info>.*?)' when", re.S)
    statistics_result = dict.fromkeys(terminalreporter._known_types)
    total = terminalreporter._numcollected
    statistics_result["total"] = total

    for stats in terminalreporter._known_types:
        if stats in ["failed", "error"]:
            failed_cases.extend([path_info_re.search(str(i)).group("info") for i in terminalreporter.getreports(stats)])
        statistics_result[stats] = len(terminalreporter.getreports(stats))

    statistics_result["failed_cases"] = "<br/>".join(failed_cases) or "无"
    duration = seconds_to_time(int(time.time() - terminalreporter._sessionstarttime))
    statistics_result["duration"] = duration
    try:
        pass_rate = round(statistics_result.get("passed") / (total - statistics_result.get("skipped")) * 100, 2)
    except ZeroDivisionError:
        pass_rate = 100
    statistics_result["pass_rate"] = pass_rate

    return TestMetrics(**statistics_result)


def generate_report():
    set_allure_environment()
    if platform.platform() == "Linux":
        return
    cmd = "allure generate ./reports/temps -o ./reports/html --clean"
    os.system(cmd)


def set_allure_environment():
    """生成allure的环境信息"""
    environment = list()
    project_name = Config().get_conf("project_name")
    environment.append(f"Project={project_name}\n")
    pl = platform.platform()
    pl = pl[:pl.index("-")]
    environment.append(f"Platform={pl}\n")
    python_version = platform.python_version()
    environment.append(f"Python={python_version}\n")
    allure_version = "2.13.1"
    environment.append(f"Allure={allure_version}\n")

    with open(os.path.join(BASE_PATH, "reports/temps/environment.properties"), "w") as f:
        f.writelines(environment)
